﻿using System;
using System.Web.Mvc;
using System.Text;
using DTcms.Common;
using System.Web.UI;
using System.Web;
using System.IO;

namespace DTcms.Web.Mvc.UI
{
    public class ManageController : Controller
    {
        protected internal Model.siteconfig siteConfig = new BLL.siteconfig().loadConfig();
        public const string EDIT_RESULT_VIEW = "~/Areas/Admin/Views/Shared/EditResult.cshtml";

        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            //CheckRoot();
            if (!validateAdminPermission())
            {
                ViewBag.Title = "受限访问";
                ViewBag.Message = "抱歉, 系统设置了IP访问列表限制, 您无法访问本网站！";
                filterContext.Result = Content(GetHTML("~/Views/Shared/BaseError.cshtml"));
                return;
            }
            if (!IsAdminLogin())
            {
                filterContext.Result = Redirect("../home/login");
                return;
            }
            base.OnAuthorization(filterContext);
        }

        #region 处理压缩HTML
        /// <summary>
        ///StringBuilder
        /// </summary>
        private StringBuilder _builder;

        /// <summary>
        ///HttpWriter
        /// </summary>
        private HttpWriter _output;

        /// <summary>
        /// 在执行Action的时候，就把需要的Writer存起来
        /// </summary>
        /// <param name="filterContext">上下文</param>
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (siteConfig.admingzip == 1)
            {
                _builder = new StringBuilder();
                StringWriter _writer = new StringWriter(_builder);
                HtmlTextWriter _htmlWriter = new HtmlTextWriter(_writer);
                _output = (HttpWriter)filterContext.RequestContext.HttpContext.Response.Output;
                filterContext.RequestContext.HttpContext.Response.Output = _htmlWriter;
                base.OnActionExecuting(filterContext);
            }
        }

        /// <summary>
        /// 在执行完成后，处理得到的HTML，并将他输出到前台
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            if (siteConfig.admingzip == 1)
            {
                var response = Utils.GzipHtml(_builder.ToString());
                _output.Write(response);
            }
        }
        #endregion

        #region 校验管理员是否可以访问
        //获取模板页面html代码
        public string GetHTML(string path)
        {
            IView view = ViewEngines.Engines.FindView(this.ControllerContext, path, string.Empty).View;
            if (view != null)
            {
                using (System.IO.StringWriter writer = new System.IO.StringWriter())
                {
                    ViewContext viewcontext = new ViewContext(this.ControllerContext, view, this.ViewData, this.TempData, writer);
                    viewcontext.View.Render(viewcontext, writer);
                    return writer.ToString();
                }
            }
            else
            {
                throw new Exception(string.Format("模板\"{0}\"不存在", path));
            }
        }

        public bool validateAdminPermission()
        {
            // 如果IP访问列表有设置则进行判断
            if (!string.IsNullOrEmpty(siteConfig.AdminIpAccess) && siteConfig.AdminIpAccess.Trim() != "")
            {
                string[] regctrl = Utils.SplitString(siteConfig.IpDenyAccess, "\n");
                return Utils.InIPArray(DTRequest.GetIP(), regctrl);
            }
            return true;
        }

        /// <summary>
        /// 获取模板页面html代码
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private string getHTML(string path)
        {
            IView view = ViewEngines.Engines.FindView(this.ControllerContext, path, string.Empty).View;
            if (view != null)
            {
                using (System.IO.StringWriter writer = new System.IO.StringWriter())
                {
                    ViewContext viewcontext = new ViewContext(this.ControllerContext, view, this.ViewData, this.TempData, writer);
                    viewcontext.View.Render(viewcontext, writer);
                    return writer.ToString();
                }
            }
            else
            {
                throw new Exception(string.Format("模板\"{0}\"不存在", path));
            }
        }
        #endregion

        #region 管理员
        #region 判断管理员是否已经登录(解决Session超时问题)
        /// <summary>
        /// 判断管理员是否已经登录(解决Session超时问题)
        /// </summary>
        public bool IsAdminLogin()
        {
            //如果Session为Null
            if (System.Web.HttpContext.Current.Session[DTKeys.SESSION_ADMIN_INFO] != null)
            {
                return true;
            }
            else
            {
                //检查Cookies
                string adminname = Utils.GetCookie("AdminName", "DTcms");
                string adminpwd = Utils.GetCookie("AdminPwd", "DTcms");
                //cookies密码解密
                try
                {
                    //用户名加密
                    adminname = DESEncrypt.Decrypt(adminname, DTKeys.COOKIE_KEY);
                    //密码绑定IP
                    adminpwd = DESEncrypt.Decrypt(adminpwd, DTRequest.GetIP());
                }
                catch
                {
                    return false;
                }
                if (adminname != "" && adminpwd != "")
                {
                    BLL.manager bll = new BLL.manager();
                    Model.manager model = bll.GetModel(adminname, adminpwd);
                    if (model != null)
                    {
                        System.Web.HttpContext.Current.Session[DTKeys.SESSION_ADMIN_INFO] = model;
                        return true;
                    }
                }
            }
            return false;
        }
        #endregion

        #region 取得管理员信息
        /// <summary>
        /// 取得管理员信息
        /// </summary>
        public Model.manager GetAdminInfo()
        {
            if (IsAdminLogin())
            {
                Model.manager model = System.Web.HttpContext.Current.Session[DTKeys.SESSION_ADMIN_INFO] as Model.manager;
                if (model != null)
                {
                    return model;
                }
            }
            return null;
        }
        #endregion

        #region 检查管理员权限
        /// <summary>
        /// 检查管理员权限
        /// </summary>
        /// <returns></returns>
        public Model.manager_role GetAdminRole()
        {
            Model.manager model = GetAdminInfo();
            return new BLL.manager_role().GetModel(model.role_id);
        }
        #endregion

        #region 检查管理员权限
        /// <summary>
        /// 检查管理员权限
        /// </summary>
        /// <param name="nav_name">菜单名称</param>
        /// <param name="action_type">操作类型</param>
        public void ChkAdminLevel(string nav_name, string action_type)
        {
            Model.manager model = GetAdminInfo();
            BLL.manager_role bll = new BLL.manager_role();
            bool result = bll.Exists(model.role_id, nav_name, action_type);

            if (!result)
            {
                string msgbox = "parent.os.jsdialog(\"错误提示\", \"您没有管理该页面的权限，请勿非法进入！\", \"back\")";
                Response.Write("<script type=\"text/javascript\">" + msgbox + "</script>");
                Response.End();
            }
        }
        #endregion

        #region 检查管理员权限
        /// <summary>
        /// 检查管理员权限
        /// </summary>
        /// <param name="nav_name">菜单名称</param>
        /// <param name="action_type">操作类型</param>
        public void ChkAdminLevel(string nav_name, string action_type, out Model.manager_role rolemodel)
        {
            Model.manager model = GetAdminInfo();
            BLL.manager_role bll = new BLL.manager_role();
            bool result = bll.Exists(model.role_id, nav_name, action_type, out rolemodel);
            if (!result)
            {
                string msgbox = "parent.os.jsdialog(\"错误提示\", \"您没有管理该页面的权限，请勿非法进入！\", \"back\")";
                Response.Write("<script type=\"text/javascript\">" + msgbox + "</script>");
                Response.End();
            }
        }
        #endregion

        #region 抛弃（2017-07-15）
        public bool ChkAuthority(string nav_name, string action_type)
        {
            Model.manager model = GetAdminInfo();
            BLL.manager_role bll = new BLL.manager_role();
            bool result = bll.Exists(model.role_id, nav_name, action_type);

            if (result)
            {
                return true;
            }
            return false;
        }
        #endregion

        #region 写入管理日志
        /// <summary>
        /// 写入管理日志
        /// </summary>
        /// <param name="action_type"></param>
        /// <param name="remark"></param>
        /// <returns></returns>
        public bool AddAdminLog(string action_type, string remark)
        {
            if (siteConfig.logstatus > 0)
            {
                Model.manager model = GetAdminInfo();
                int newId = new BLL.manager_log().Add(model.id, model.user_name, action_type, remark);
                if (newId > 0)
                {
                    return true;
                }
            }
            return false;
        }
        #endregion
        #endregion

        #region JS提示
        /// <summary>
        /// 添加编辑删除提示
        /// </summary>
        /// <param name="msgtitle">提示文字</param>
        /// <param name="url">返回地址</param>
        public ActionResult ResultMsg(string msgtitle, string url)
        {
            ActionResult result = View(EDIT_RESULT_VIEW);
            string msbox = "<script type=\"text/html\" id=\"ClientScript\">os.jsprint(\"" + msgtitle + "\", \"" + url + "\")</script>";
            ViewBag.ClientScript = msbox;
            return result;
        }
        /// <summary>
        /// 带回传函数的添加编辑删除提示
        /// </summary>
        /// <param name="msgtitle">提示文字</param>
        /// <param name="url">返回地址</param>
        /// <param name="callback">JS回调函数</param>
        public ActionResult ResultMsg(string msgtitle, string url, string callback)
        {
            ActionResult result = View(EDIT_RESULT_VIEW);
            string msbox = "<script type=\"text/html\" id=\"ClientScript\">os.jsprint(\"" + msgtitle + "\", \"" + url + "\", " + callback + ")</script>";
            ViewBag.ClientScript = msbox;
            return result;
        }
        /// <summary>
        /// JS输出代码
        /// </summary>
        /// <param name="jscript">JS代码</param>
        public string Jscript(string jscript)
        {
            string msbox = "<script type=\"text/html\" id=\"ClientScript\">" + jscript + "</script>";
            return msbox;
        }
        /// <summary>
        /// 添加编辑删除提示
        /// </summary>
        /// <param name="msgtitle">提示文字</param>
        /// <param name="url">返回地址</param>
        public string JscriptMsg(string msgtitle, string url)
        {
            string msbox = "<script type=\"text/html\" id=\"ClientScript\">os.jsprint(\"" + msgtitle + "\", \"" + url + "\")</script>";
            return msbox;
        }
        /// <summary>
        /// 带回传函数的添加编辑删除提示
        /// </summary>
        /// <param name="msgtitle">提示文字</param>
        /// <param name="url">返回地址</param>
        /// <param name="callback">JS回调函数</param>
        public string JscriptMsg(string msgtitle, string url, string callback)
        {
            string msbox = "<script type=\"text/html\" id=\"ClientScript\">os.jsprint(\"" + msgtitle + "\", \"" + url + "\", " + callback + ")</script>";
            return msbox;
        }
        #endregion

        #region 重写JsonResult
        protected override JsonResult Json(object data, string contentType, Encoding contentEncoding)
        {
            return new CustomJsonResult { Data = data, ContentType = contentType, ContentEncoding = contentEncoding };
        }

        public new JsonResult Json(object data, JsonRequestBehavior jsonRequest)
        {
            return new CustomJsonResult { Data = data, JsonRequestBehavior = jsonRequest };
        }

        public new JsonResult Json(object data)
        {
            return new CustomJsonResult { Data = data, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }
        #endregion

        #region Attribute权限验证
        public class ChkAdminJsonAttribute : ActionFilterAttribute
        {
            //菜单名称
            public string nav_name { get; set; }

            //操作类型
            public string action_type { get; set; }

            public ChkAdminJsonAttribute(string name, DTEnums.ActionEnum type)
            {
                this.nav_name = name;
                this.action_type = type.ToString();
            }
            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                ManageController _base = new ManageController();

                Model.manager model = _base.GetAdminInfo();
                BLL.manager_role bll = new BLL.manager_role();
                bool result = bll.Exists(model.role_id, nav_name, action_type);
                if (!result)
                {
                    string values = Utils.ActionType()[action_type];
                    filterContext.Result = new JsonResult
                    {
                        Data = new { status = 0, url = "", msg = string.Format("您没有该页面的【{0}】权限！", values) },
                        ContentEncoding = Encoding.UTF8,
                        ContentType = "application/json",
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    };
                    #region 写入操作记录
                    new BLL.manager_log().Add(model.id, model.user_name, action_type, string.Format("没有页面的【{0}】权限！", values));
                    #endregion
                }
                base.OnActionExecuting(filterContext);
            }
        }
        public class ChkAdminScriptAttribute : ActionFilterAttribute
        {
            //菜单名称
            public string nav_name { get; set; }

            //操作类型
            public string action_type { get; set; }

            public ChkAdminScriptAttribute(string name, DTEnums.ActionEnum type)
            {
                this.nav_name = name;
                this.action_type = type.ToString();
            }
            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                ManageController _base = new ManageController();

                Model.manager model = _base.GetAdminInfo();
                BLL.manager_role bll = new BLL.manager_role();
                bool result = bll.Exists(model.role_id, nav_name, action_type);
                if (!result)
                {
                    string values = Utils.ActionType()[action_type];
                    string msgbox = string.Format("parent.os.jsdialog(\"错误提示\", \"您没有管理该页面的权限，请勿非法进入！\", \"\")");
                    filterContext.Result = new ContentResult()
                    {
                        Content = "<script type=\"text/javascript\">" + msgbox + "</script>",
                        ContentEncoding = Encoding.UTF8,
                        ContentType = "text/html"
                    };
                    #region 写入操作记录
                    new BLL.manager_log().Add(model.id, model.user_name, action_type, "管理该页面的权限，非法进入！");
                    #endregion
                }
                base.OnActionExecuting(filterContext);
            }
        }
        #endregion
    }
}
